package com.xiaobaibai.units;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xiaobaibai.bo.SubscribeMessageBo;
import com.xiaobaibai.common.WeixinCommon;
import com.xiaobaibai.entity.User;
import com.xiaobaibai.service.IUserService;
import com.xiaobaibai.threadPool.MyThreadPoolUnit;
import com.xiaobaibai.units.pay.HttpClientUnit;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

@Component
@Slf4j
public class OrderWXNewsUnit implements ApplicationRunner, DisposableBean {

    /**
     * 订单消息通知
     */
    @Autowired
    private IUserService userService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private final String getTokenUrl="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s";

    private final String sendNewsUrl="https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=%s";

    public static String token=null;//接口调用凭证

    private String url="";

    //下单成功提醒(货到付款/微信支付后)
    private final String okOrderNewId ="a-5g2jAfvr-QqhuvQBu4pHbbjQSFYZ10QkXzK_hCPgo";

    //确认收货后提醒
    private final String completeOrderNewId ="8yy-h3RHIBkWDSP28K_H4Dr7A8LXdEJnuv2Sh-tUStg";

    //下单成功(付款后+选择货到付款)
    public void sendOkOrderNew(String phone,Integer userId,String orderId,String productNames,
                               String address){
        if(productNames.length()>18)
            productNames=productNames.substring(0,15)+"...";
        final String productNames2=productNames;
        if(address.length()>20)
            address=address.substring(0,18)+"...";
        final String address2=address;
        CompletableFuture.runAsync(()->{
            QueryWrapper<User> q1=new QueryWrapper<>();
            q1.select("user_openid");
            q1.eq("user_id",userId);
            User user = userService.getOne(q1);
            Map<String,String> map=new HashMap<>();
            map.put("character_string2",orderId);
            map.put("thing11",productNames2);
            map.put("thing8",address2);
            map.put("phrase10","等待送达");
            map.put("thing7","商品正快马加鞭向您奔来");
            SubscribeMessageBo subscribeMessageBo=
                    new SubscribeMessageBo(token,user.getUserOpenid(), okOrderNewId,map);
            JSONObject jsonObject = HttpClientUnit.messagePost(url, subscribeMessageBo);
            if(jsonObject.getInteger("errcode")!=0){
                SmsUnit.sendCreateOkOrder(phone,orderId,productNames2,address2,
                        "等待送达","商品正快马加鞭向您奔来");
            }
        }, MyThreadPoolUnit.threadPoolExecutor);
    }

    //确认收货后
    public void sendCompeteOrder(String phone,Integer userId,String orderId){
        CompletableFuture.runAsync(()->{
            QueryWrapper<User> q1=new QueryWrapper<>();
            q1.eq("user_id",userId);
            q1.select("user_openid");
            User user = userService.getOne(q1);
            Map<String,String> map=new HashMap<>();
            map.put("character_string10",orderId);
            map.put("thing1","已完成");
            map.put("date2",DateFormatUtils.format(new Date(), "yyyy年MM月dd日 HH:mm"));
            map.put("thing12","谢谢亲的惠顾,期待下次为您服务");
            SubscribeMessageBo subscribeMessageBo=
                    new SubscribeMessageBo(token,user.getUserOpenid(), completeOrderNewId,map);
            JSONObject jsonObject = HttpClientUnit.messagePost(url, subscribeMessageBo);
            if(jsonObject.getInteger("errcode")!=0){
                SmsUnit.sendConfirmOrder(phone,orderId,"已完成","谢谢亲的惠顾,期待下次为您服务");
            }
        }, MyThreadPoolUnit.threadPoolExecutor);
    }

    @Override
    public void run(ApplicationArguments args) {
        /**
         * 客户端每个小时的53分去获取token,并且存入redis也存入本地
         * 服务端每个小时的55分去redis中获取token存入本地
         */
        String url = String.format(getTokenUrl, WeixinCommon.APPID,WeixinCommon.SECRET);
        JSONObject jsonObject = HttpClientUnit.get(url);
        if(jsonObject.getString("access_token")==null) {
            jsonObject = HttpClientUnit.get(url);
            if(jsonObject.getString("access_token")==null)
                throw new RuntimeException("token获取不到");
        }
        token= jsonObject.getString("access_token");
        this.url=String.format(sendNewsUrl,token);
        //每次启动也要放置好,不用担心redis缓存是永久的,因为本容器摧毁时会delete掉token
        stringRedisTemplate.opsForValue().set(WeixinCommon.WxAccessToken,token);
    }

    @Override
    public void destroy() throws Exception {
        stringRedisTemplate.delete(WeixinCommon.WxAccessToken);//删除给管理端的微信发送消息的token,防止下次两个一起启动时管理端拿错了token
    }
}
